//
// Created by 86135 on 2025-06-24.
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "symbol_table.h"

#define TABLE_SIZE 100

// 初始化符号表
SymbolTable* initSymbolTable(SymbolTable* parent) {
    SymbolTable* table = (SymbolTable*)malloc(sizeof(SymbolTable));
    table->entries = (SymbolTableEntry**)calloc(TABLE_SIZE, sizeof(SymbolTableEntry*));
    table->size = TABLE_SIZE;
    table->parent = parent;
    return table;
}

// 哈希函数
unsigned int hash(const char* name) {
    unsigned int hashval = 0;
    for (int i = 0; name[i] != '\0'; i++) {
        hashval = name[i] + (hashval << 6) + (hashval << 16) - hashval;
    }
    return hashval % TABLE_SIZE;
}

// 插入符号
void insertSymbol(SymbolTable* table, const char* name, ASTNode* type) {
    unsigned int index = hash(name);
    SymbolTableEntry* entry = (SymbolTableEntry*)malloc(sizeof(SymbolTableEntry));
    entry->name = strdup(name);
    entry->type = type;
    entry->next = table->entries[index];
    table->entries[index] = entry;
}

// 查找符号
SymbolTableEntry* lookupSymbol(SymbolTable* table, const char* name) {
    unsigned int index = hash(name);
    SymbolTableEntry* entry = table->entries[index];
    while (entry != NULL) {
        if (strcmp(entry->name, name) == 0) {
            return entry;
        }
        entry = entry->next;
    }
    if (table->parent != NULL) {
        return lookupSymbol(table->parent, name);
    }
    return NULL;
}

// 销毁符号表
void destroySymbolTable(SymbolTable* table) {
    for (int i = 0; i < table->size; i++) {
        SymbolTableEntry* entry = table->entries[i];
        while (entry != NULL) {
            SymbolTableEntry* next = entry->next;
            free(entry->name);
            free(entry);
            entry = next;
        }
    }
    free(table->entries);
    free(table);
}
